package com.egoo.ticket.server.utils.activiti.command;

import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.ActivitiEngineAgenda;
import org.activiti.engine.ManagementService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityManager;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;

/**
 * @Auther: victor_tang
 * @Date: 2020/8/12 15:02
 * @Description: activit6节点自由跳转命令类
 */
public class Jump2TargetFlowNodeCommand implements Command {
    /**
     * 创建流程引擎对象
     */
    public static ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
    String _targetFlowNodeId;
    String _curTaskId;
    public Jump2TargetFlowNodeCommand(String curTaskId, String targetFlowNodeId)
    {
        this._curTaskId = curTaskId;
        this._targetFlowNodeId = targetFlowNodeId;
    }
    /**
     * TODO 重写命令类
     * @author: victor_tang
     * @createtime: 2020/8/12 14:21
     * @param commandContext 1
     * @return: java.lang.Object
     */
    @Override
    public Object execute(CommandContext commandContext) {
        System.out.println("跳转到目标流程节点：" + _targetFlowNodeId);
        ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
        TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
        // 获取当前任务的来源任务及来源节点信息
        TaskEntity taskEntity = taskEntityManager.findById(_curTaskId);
        ExecutionEntity executionEntity = executionEntityManager.findById(taskEntity.getExecutionId());
        Process process = ProcessDefinitionUtil.getProcess(executionEntity.getProcessDefinitionId());
        // 删除当前节点
        taskEntityManager.deleteTask(taskEntity, "", true, true);
        // 获取要跳转的目标节点
        FlowElement targetFlowElement =
                process.getFlowElement(_targetFlowNodeId);
        executionEntity.setCurrentFlowElement(targetFlowElement);
        ActivitiEngineAgenda agenda = commandContext.getAgenda();
        agenda.planContinueProcessInCompensation(executionEntity);
        return null;
    }

    /**
     * 跳转到指定流程节点
     *
     * @param curTaskId
     * @param targetFlowNodeId
     *            指定的流程节点ID 比如跳转<endEvent id="endevent1" name="End"></endEvent> ，则targetFlowNodeId为endevent1
     */
    public static void jump2TargetFlowNode(String curTaskId, String targetFlowNodeId) {
        ManagementService managementService = processEngine.getManagementService();
        managementService.executeCommand(new Jump2TargetFlowNodeCommand(curTaskId, targetFlowNodeId));
    }
}
